package com.gcxy.shop.common;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.shop.common.JdbcUtils;


/**
 * Jdbc的公共类
 * @author Administrator
 *
 */
public class JdbcUtils {
     private static String username="";
     private static String password="";
     private static String url="";
     private static Logger logger=LoggerFactory.getLogger(JdbcUtils.class);
     
     static{ 
    		 try {
    				//读取配置文件
    				Properties prop=new Properties();
    				InputStream inputStream=JdbcUtils.class.getResourceAsStream("/jdbc.properties");
    				prop.load(inputStream);
    				//获取配置参数
    				username=prop.getProperty("jdbc.username");
    				password=prop.getProperty("jdbc.password");
    				url=prop.getProperty("jdbc.url");
    				
    				Class.forName(prop.getProperty("jdbc.driver"));
    				logger.debug("初始化mysql驱动");
    			} catch (ClassNotFoundException | IOException e) {
    				logger.error("初始化驱动或读取参数异常:{}",e.getMessage());
    			}
		}
     /**
      * 获取数据库连接的公共类
      * @return
      */
     public static Connection getConnection() {
		try {
			logger.debug("数据库连接成功");
			return DriverManager.getConnection(url,username,password);
		} catch (Exception e) {
			logger.error("获取数据库连接异常：{}",e.getMessage());
			return null;
		}
	}
     public static void close(Connection conn,PreparedStatement ps,ResultSet rs) {
		try {
			if(rs!=null){
				rs.close();
				}
				
		} catch (Exception e) {
			logger.error("关闭ResultSet资源异常：{}",e.getMessage());
		}finally {
			try {
				if(ps!=null) {
					ps.close();
			} 
			}catch (Exception e2) {	
				logger.error("关闭Statement资源异常：{}",e2.getMessage());
		}finally {
			try {
				if(conn!=null) {
					conn.close();
				}
			} catch (Exception e3) {
				logger.error("关闭Connection资源异常：{}",e3.getMessage());
			}
		}
		}
     }
	
		
}